package org.mclll.xwangplugin.town.command.executor;

import com.alibaba.fastjson.JSON;
import de.tr7zw.nbtapi.NBT;
import de.tr7zw.nbtapi.iface.ReadWriteNBT;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.mclll.xwangplugin.town.database.domain.TownDO;
import org.mclll.xwangplugin.town.database.mapper.manage.TownManage;

import java.util.List;

import static org.mclll.xwangplugin.town.config.TownContext.*;

public class TownSetWarpExecutor {
    public static void setTp(Player player, String[] args) {
        String townName, title;
        if (args.length == 3) {
            townName = args[1];
            title = args[2];
        } else {
            player.sendMessage(TOWN_SET_TP_COMMAND_FORMAT);
            return;
        }

        TownDO town = new TownDO();
        town.setName(townName);
        List<TownDO> townList = TownManage.selectList(town);
        if (townList.isEmpty()) {
            player.sendMessage(TOWN_NOT_FOUND);
            return;
        }
        town = townList.get(0);
        TownDO.StarDoor starDoor = new TownDO.StarDoor();
        Location location = player.getLocation();
        starDoor.setPos(String.format("%d %d %d %s", location.getBlockX(), location.getBlockY(), location.getBlockZ(), location.getWorld().getName()));
        ItemStack itemInMainHand = player.getInventory().getItemInMainHand();
//        if (itemInMainHand.getType() == Material.AIR) {
//            starDoor.setType(Material.STONE);
//        } else {
//            starDoor.setType(itemInMainHand.getType());
//        }
        if (itemInMainHand.getType() == Material.AIR) {
            ReadWriteNBT readWriteNBT = NBT.itemStackToNBT(new ItemStack(Material.STONE));
            starDoor.setType(readWriteNBT.toString());
        } else {
            ReadWriteNBT readWriteNBT = NBT.itemStackToNBT(itemInMainHand);
            starDoor.setType(readWriteNBT.toString());
        }
        starDoor.setTitle(title);
        town.setStarDoorJson(JSON.toJSONString(starDoor));
        TownManage.updateByUuid(town);
        player.sendMessage(String.format(TOWN_SET_TP_SUCCESS, townName));
    }
}
